import {ref, watch} from "vue"
import store from "@/store"
import {defineStore} from "pinia"
import {useTagsViewStore} from "./tags-view"
import {useSettingsStore} from "./settings"
import {getToken, removeToken, setToken} from "@/utils/cache/cookies"
import {resetRouter} from "@/router"
import {getUserInfoApi, loginApi, logoutApi, updateUserSysConfig} from "@/api/login"
import {type LoginRequestData} from "@/api/login/types/login"
import routeSettings from "@/config/route"
import {StringUtils} from "@/utils/StringUtils";
import {deepClone} from "@/utils";
import {merge as deepMerge} from 'lodash';

export interface HistoryItem {
  time: number; // 单位s
  path: string;
}

export const UserSysConfigDefault = {
  video: {
    playbackRate: 1,
    historyList: [] as HistoryItem[],
  },
  music: {
    volume: 0.2,
    playType: '单曲循环',
  }
}


export const useUserStore = defineStore("user", () => {
  const token = ref<string>(getToken() || "")
  const roles = ref<string[]>([])
  const auths = ref<string[]>([])
  const username = ref<string>("")
  const userSysConfig = ref(deepClone(UserSysConfigDefault))

  const tagsViewStore = useTagsViewStore()
  const settingsStore = useSettingsStore()

  /** 登录 */
  const login = async ({username, password, code}: LoginRequestData) => {
    const {data} = await loginApi({username, password, code})
    setToken(data.token)
    token.value = data.token
  }
  /** 获取用户详情 */
  const getInfo = async () => {
    const {data} = await getUserInfoApi()
    username.value = data.username
    // 验证返回的 roles 是否为一个非空数组，否则塞入一个没有任何作用的默认角色，防止路由守卫逻辑进入无限循环
    roles.value = data.roleName ? data.roleName.split(StringUtils.split) : routeSettings.defaultRoles
    auths.value = data.auths ? data.auths.split(StringUtils.split) : []
    if (data.userSysConfig) {
      try {
        let json = JSON.parse(data.userSysConfig)
        if (json) {
          userSysConfig.value = deepMerge({}, UserSysConfigDefault, json)
        }
      } catch (e) {
      }
    }
    watch(() => userSysConfig, (value) => {
      let data = value.value
      updateUserSysConfig(data)
    }, {deep: true})
  }
  /** 模拟角色变化 */
  const changeRoles = async (role: string) => {
    const newToken = "token-" + role
    token.value = newToken
    setToken(newToken)
    // 用刷新页面代替重新登录
    window.location.reload()
  }
  /** 登出 */
  const logout = async () => {
    logoutApi()
    removeToken()
    token.value = ""
    roles.value = []
    resetRouter()
    _resetTagsView()
  }
  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    token.value = ""
    roles.value = []
  }
  /** 重置 Visited Views 和 Cached Views */
  const _resetTagsView = () => {
    if (!settingsStore.cacheTagsView) {
      tagsViewStore.delAllVisitedViews()
      tagsViewStore.delAllCachedViews()
    }
  }

  function pushHistory(item: HistoryItem, historyList: HistoryItem[]) {
    let finIndex = historyList.findIndex(i => i.path === item.path)
    if (finIndex > -1) {
      historyList.splice(finIndex, 1)
    }
    historyList.unshift(item)
    let saveLength = 20
    if (historyList.length > saveLength) {
      historyList.splice(saveLength, historyList.length - saveLength)
    }
  }

  function pushVideoHistory(item: HistoryItem) {
    const historyList = userSysConfig.value.video.historyList
    pushHistory(item, historyList)
  }

  return {
    token,
    roles,
    auths,
    username,
    userSysConfig,
    pushVideoHistory,
    login,
    getInfo,
    changeRoles,
    logout,
    resetToken
  }
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
